package cn.zb.config;

import com.alibaba.cloud.commons.io.Charsets;
import com.alibaba.fastjson2.JSON;
import lombok.SneakyThrows;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:认证异常配置类
 * @Author:
 * @Date: 2024/11/22 18:42
 */
@Component
public class AuthException implements ServerAuthenticationEntryPoint  {

    @SneakyThrows
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        ServerHttpResponse response = exchange.getResponse();
        Map<String,Object> map = new HashMap<>();
        map.put("code",401);

        if(ex instanceof LockedException){
            map.put("msg","账号被锁定 请联系管理员");
        }else{
            map.put("msg","认证失败");
        }
        String s = JSON.toJSONString(map);
        DataBuffer db = response.bufferFactory().wrap(s.getBytes());
        // 设置编码
        response.getHeaders().set("content-type","application/json;charset=utf-8");
        return response.writeWith(Mono.just(db));
    }

}